package Worker;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
import Interfaces.*;

public class Worker implements WorkerInterface{
	
	private static String uniqueID = UUID.randomUUID().toString();
	
	@Override
	public void doTask(Task task) throws RemoteException{
		task.execute();
	}
	
	public static void main(String args[]) {
		
		if (System.getSecurityManager() == null) {
			System.setSecurityManager(new SecurityManager());
		}
		
		try {
			// installing a remote object for treating client jobs at the remote rmiregistry
			WorkerInterface worker= new Worker();
			Registry registry = LocateRegistry.getRegistry(args[0]);
            
            WorkerInterface stub = (WorkerInterface)
            						UnicastRemoteObject.exportObject(worker,0);
            registry.rebind(uniqueID, stub);
			
            // getting the remote stub for worker registration
			String name = "Register";
			WorkerRegister regObj = (WorkerRegister) registry.lookup(name);
			
			Set<String> resources = new  TreeSet<String>();
			for(int i=1;i<args.length;i++) {
				resources.add(args[i]);
			}
			// registering to the master machine
			regObj.register(uniqueID,resources);
			
		} catch (Exception e) {
			System.exit(-1);
		}
	}   
	
}
